package com.wkl.yuyue.controller;

import com.wkl.yuyue.entity.Classes;
import com.wkl.yuyue.entity.Course;
import com.wkl.yuyue.entity.Department;
import com.wkl.yuyue.service.IClassesService;
import com.wkl.yuyue.service.ICourseService;
import com.wkl.yuyue.service.IDepService;
import com.wkl.yuyue.utils.AuthenticationContextHolder;
import com.wkl.yuyue.entity.User;
import com.wkl.yuyue.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 * 登录 处理器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-05-05
 */

@Controller
public class LoginController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IClassesService iClassesService;
    @Autowired
    private IDepService iDepService;
    @Autowired
    private ICourseService iCourseService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @GetMapping("/toLoginPage")
    public String toLoginPage(Model model){
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }

    /**
     * 默认跳转登录页面
     * @param modelAndView
     * @return
     */
    @GetMapping("/")
    public ModelAndView loginStart(ModelAndView modelAndView){
        modelAndView.setViewName("login");
        return modelAndView;
    }

    /**
     * 登录判断
     * @param user
     * @param modelAndView
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/login2")
    public ModelAndView loginIndex(User user, ModelAndView modelAndView,
                                   HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Authentication authentication = null;
        if(user.getUserId() == null){
            request.setAttribute("result", "none1");
            response.sendRedirect("/toLoginPage");
        }else if(user.getPassword() == null | user.getPassword() == "" ){
            request.setAttribute("result", "none2");
            response.sendRedirect("/toLoginPage");
        }else {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    user.getUserId(), user.getPassword()
            );
            AuthenticationContextHolder.setUserNamePasswordInfo(usernamePasswordAuthenticationToken);
            authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            if(authentication!=null){
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            User user2 = (User) authentication.getPrincipal();
            List<Classes> classesList = iClassesService.findClassesAll();
            List<Department> deptList = iDepService.findDepAll();
            List<Course> courseList = iCourseService.findCourseAll();
            if (user2 == null) {
                request.setAttribute("result", "full");
                response.sendRedirect("/toLoginPage");
            } else {
                    request.getSession().setAttribute("user", user2);
                    request.getSession().setAttribute("classesList", classesList);
                    request.getSession().setAttribute("deptList", deptList);
                    request.getSession().setAttribute("courseList", courseList);
                    modelAndView.setViewName("index");
                    return modelAndView;

            }
        }

        modelAndView.setViewName("login");
        return modelAndView;
    }

    /**
     * 测试页面List
     * @param modelAndView
     * @return
     */
    @GetMapping("/formTestList")
    public ModelAndView formTestList(ModelAndView modelAndView){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        if(user.getFullName().equals("超级管理员")){
            modelAndView.setViewName("test/test_list");
        }
        else {
            modelAndView.setViewName("test/test_list2");
        }
        return modelAndView;
    }
    @GetMapping("/toRegister")
    public ModelAndView register(ModelAndView modelAndView){
        modelAndView.setViewName("register");
        return modelAndView;
    }
    @PostMapping("/register")
    public ModelAndView register2(ModelAndView modelAndView,HttpServletRequest request) throws IOException {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String userId = request.getParameter("userId");
        String password = request.getParameter("password");
        User user = new User();
        user.setPassword(encoder.encode(password));
        user.setUserId(userId);
        String uploadPath = ResourceUtils.getURL("classpath:static").getPath()+ "/img/"+userId+"blob.png";
        String path = ResourceUtils.getURL("classpath:static").getPath()+ "/img"+"/blob.png";
        FileInputStream fileInputStream = new FileInputStream(path);
        FileOutputStream fileOutputStream = new FileOutputStream(uploadPath,true);
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(b)) != -1){
            //注意不能直接用write(b)，因为读到最后是不满一个数组大小的，还按一个数组来写就会出错
            fileOutputStream.write(b,0,len);
        }
        user.setAvatar("/img/"+userId+"blob.png");
        user.setTelephone(request.getParameter("phone"));
        user.setFullName(request.getParameter("role"));
        iUserService.addUser(user);
        modelAndView.setViewName("login");
        return modelAndView;
    }

}
